package com.gui.juc.base.safe;

import com.gui.utils.Sleeper;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class ThreadSafeDemo1 {

    public static void main(String[] args) {

        for (int i = 0; i < 10; i++) {
            Child child = new Child();
            child.addAndRemove();
        }
    }
}


class Parent {

    protected List<String> get() {
        ArrayList<String> list = new ArrayList<>();
        return list;
    }
}

@Slf4j
class Child extends Parent {

    public void addAndRemove() {
        List<String> list = get();

        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                list.add("Hello World!!");
            }
        }, "t1");

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                list.add("Java");
            }
        }, "t2");

        t1.start();
        t2.start();

        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            log.error("被打断...");
        }
        log.debug("result: {}", list.size());
        log.debug("========================================");
    }
}
